<?php


namespace app\admin\service\base;


use app\admin\model\base\Classes;
use app\admin\model\base\Grades;
use app\admin\model\base\Paper;
use app\admin\model\base\Paper as Question;
use app\admin\model\base\PaperSubject;
use app\admin\model\base\Special;
use app\admin\model\base\Student;
use app\admin\model\base\StudentPaper;
use app\admin\validates\PaperValidate;
use app\BaseService;
use export\Export;
use think\exception\ValidateException;
use think\response\Json;

class PaperService extends BaseService
{
    /**
     * 列表
     * @param array $params
     * @return Json
     */
    public function index(array $params): Json
    {
        $where[] = ['is_del','=',0];
        if(isset($params['special_id']) && $params['special_id']){
            $where[] = ['special_id','=',$params['special_id']];
        }
        if(isset($params['name']) && $params['name']){
            $where[] = ['name','like',"%{$params['name']}%"];
        }
        //获取列表
        $data = Question::getList($where, $params['page'] ?? 1, $params['limit'] ?? 100, 'id desc');
        return jsonReturn(1, $data);
    }

    /**
     * 导出学生数据
     * @param array $params
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function export(array $params):Json
    {
        try {
            validate(PaperValidate::class)->scene('details')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        //查询学生考试信息
        $info = Paper::findOne(['id'=>$params['id']]);
        $list = StudentPaper::where('is_del','=',0)
            ->where('paper_id','=',$params['id'])
            ->with(['student','paper'])
            ->select()
            ->toArray();
        $grades = Grades::select()->toArray();
        $grades_ids = array_column($grades,'name','id');
        $special = Special::select()->toArray();
        $special_ids = array_column($special,'name','id');
        $classes = Classes::select()->toArray();
        $classes_ids = array_column($classes,'name','id');
        $arr = [];
        $arrName = ['专业','年级','班级','学号','姓名','成绩','场次','考试时间'];
        if(!empty($list)){
            foreach ($list as $value){
                //组装导出数据
                //查询专业和年级还有班级
//                $s = Special::where('id','=',$value['special'])
                $arr[] = [
                    $special_ids[$value['student']['special_id']] ?? '暂无',
                    $grades_ids[$value['student']['grades_id']] ?? '暂无',
                    $classes_ids[$value['student']['classes_id']] ?? '暂无',
                    $value['student']['username'] ?? '暂无',
                    $value['student']['realname'] ?? '暂无',
                    $value['score'],
                    $value['paper']['name'] ?? '暂无',
                    date('Y-m-d',strtotime($value['paper']['start_time'] ?? date('Y-m-d')))
                ];
            }
        }
        $e = new Export();
        $data = $e->downloadExcel($arr,$arrName,$info['name'].'-'.date('Y-m-d'),'Xlsx');
        return jsonReturn(1, $data);
    }


    /**
     * 单个试卷考试统计
     * @param array $params
     * @return Json
     */
    public function statistics(array $params):Json
    {
        try {
            validate(PaperValidate::class)->scene('details')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        $info = Paper::findOne(['id'=>$params['id']]);
        $data = [];
        $data['reality_num'] = StudentPaper::where('is_del','=',0)->where('paper_id','=',$params['id'])->count();
        $data['pass_num'] = StudentPaper::where('is_del','=',0)
            ->where('paper_id','=',$params['id'])
            ->where('score','>=',$info['pass_score'])
            ->count();
        $data['avg_score'] = StudentPaper::where('is_del','=',0)
            ->where('paper_id','=',$params['id'])
            ->field('AVG(score) as svg_score')
            ->find()->svg_score ?? 0;
        $data['min_score'] = StudentPaper::where('is_del','=',0)
            ->where('paper_id','=',$params['id'])
            ->order('score','asc')
            ->value('score') ?? 0;
        $data['max_score'] = StudentPaper::where('is_del','=',0)
            ->where('paper_id','=',$params['id'])
            ->order('score','desc')
            ->value('score') ?? 0;
        $data['max_end_time'] = StudentPaper::where('is_del','=',0)
            ->where('paper_id','=',$params['id'])
            ->order('end_time','desc')
            ->value('end_time') ?? '';
        $data['min_end_time'] = StudentPaper::where('is_del','=',0)
            ->where('paper_id','=',$params['id'])
            ->order('end_time','asc')
            ->value('end_time') ?? '';
        $data['max_take_time'] = StudentPaper::where('is_del','=',0)
            ->where('paper_id','=',$params['id'])
            ->order('take_time','desc')
            ->value('take_time') ?? 0;
        $data['min_take_time'] = StudentPaper::where('is_del','=',0)
            ->where('paper_id','=',$params['id'])
            ->order('take_time','asc')
            ->value('take_time') ?? 0;
        return jsonReturn(1, $data);
    }

    /**
     * 单个试卷考试学生列表
     * @param array $params
     * @return Json
     */
    public function studentList(array $params):Json
    {
        try {
            validate(PaperValidate::class)->scene('details')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        $where[] = ['is_del','=',0];
        $where[] = ['paper_id','=',$params['id']];
        if(isset($params['special_id']) && $params['special_id']){
            $where[] = ['special_id','=',$params['special_id']];
        }
        if(isset($params['realname']) && $params['realname']){
            //查询学生ID
            $idList = Student::where('realname','like','%'.$params['realname'].'%')->select()->toArray();
            if($idList){
                $ids = array_column($idList,'id');
                $where[] = ['student_id','in',implode(',',$ids)];
            }else{
                $where[] = ['student_id','in','999999'];
            }

        }
        $order = 'id desc';
        if(isset($params['order']) && $params['order'] && isset($params['field']) && $params['field']){
            if(!in_array($params['order'],['desc','asc'])){
                return jsonReturn(1, [],'排序顺序只能是asc或者desc');
            }
            if(!in_array($params['field'],['score','take_time','end_time'])){
                return jsonReturn(1, [],'排序顺序只能是asc或者desc');
            }
            $order = "{$params['field']} {$params['order']}";
        }
        //获取列表
        $data = StudentPaper::getList($where, $params['page'] ?? 1, $params['limit'] ?? 100, $order);
        return jsonReturn(1, $data);
    }

    /**
     * 详情
     * @param array $params
     * @return Json
     */
    public function read(array $params): Json
    {
        try {
            validate(PaperValidate::class)->scene('details')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        $where = ['id'=>$params['id']];
        $data = Question::where($where)->with(['paper_subjects','special'])->find();
        return jsonReturn(1, $data);
    }

    /**
     * 保存
     * @param array $params
     * @return Json
     */
    public function save(array $params): Json
    {
        //数据验证
        try {
            validate(PaperValidate::class)->scene('add')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }

        $data = Question::create([
            'name'=>$params['name'],
            'sort'=>$params['sort'] ?? 1,
            'create_user'=>WS_ADMIN_ID,
            'type'=>$params['type'],
            'desc'=>$params['desc'],
            'pass_score'=>$params['pass_score'],
            'start_time'=>$params['start_time'],
            'end_time'=>date('Y-m-d H:i:s',strtotime($params['start_time'])+ ($params['time'] * 60)),
            'time'=>$params['time'],
            'special_id'=>$params['special_id'],
            'way'=>$params['way'],
            'img'=>$params['img'] ?? ''
        ]);
        if($data){
            return jsonReturn(1, []);
        }
        return jsonReturn(0, []);
    }

    /**
     * 编辑
     * @param array $params
     * @return Json
     */
    public function update(array $params): Json
    {
        try {
            validate(PaperValidate::class)->scene('edit')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        $count = StudentPaper::where('paper_id','=',$params['id'])->count();
        if($count > 0){
            return jsonReturn(0, [],'已有学生参加考试，不允许编辑');
        }
        $data = [
            'name'=>$params['name'],
            'sort'=>$params['sort'],
            'create_user'=>WS_ADMIN_ID,
            'type'=>$params['type'],
            'desc'=>$params['desc'],
            'pass_score'=>$params['pass_score'],
            'start_time'=>$params['start_time'],
            'end_time'=>date('Y-m-d H:i:s',strtotime($params['start_time']) + ($params['time'] * 60)),
            'time'=>$params['time'],
            'special_id'=>$params['special_id'],
            'way'=>$params['way'],
            'img'=>$params['img']
        ];
        $data = Question::where('id','=',$params['id'])->update($data);
        if($data){
            return jsonReturn(1, []);
        }
        return jsonReturn(1, []);
    }

    /**
     * 删除
     * @param array $params
     * @return Json
     */
    public function delete(array $params): Json
    {
        try {
            validate(PaperValidate::class)->scene('del')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }

        $count = StudentPaper::where('paper_id','=',$params['id'])->count();
        if($count > 0){
            return jsonReturn(0, [],'已有学生参加考试，不允许删除');
        }

        $data = Question::where('id','=',$params['id'])->update(['is_del'=>1]);
        if($data){
            return jsonReturn(1, []);
        }
        return jsonReturn(0, []);
    }

    /**
     * 编辑
     * @param array $params
     * @return Json
     */
    public function paperSubjectDel(array $params): Json
    {
        if(!isset($params['ids'])){
            return jsonReturn(0, [],'请选择要删除的数据');
        }
        if(empty($params['ids'])){
            return jsonReturn(0, [],'请选择要删除的数据');
        }
        $ids = implode(',',$params['ids']);
        $data = PaperSubject::where('id','in',$ids)->update(['is_del'=>1]);
        if($data){
            return jsonReturn(1, []);
        }
        return jsonReturn(0, []);
    }

    /**
     * 发布
     * @param array $params
     * @return Json
     */
    public function paperRelease(array $params): Json
    {
        if(!isset($params['type'])){
            return jsonReturn(0, [],'请选择操作类型');
        }
        if(!isset($params['id'])){
            return jsonReturn(0, [],'请选择要发布的数据');
        }
        if($params['type'] == 1){
            $is_release = 1;
        }else{
            $is_release = 0;

            $count = StudentPaper::where('paper_id','=',$params['id'])->count();
            if($count > 0){
                return jsonReturn(0, [],'已有学生参加考试，不允许编辑');
            }
        }
        $data = Paper::where('id','=',$params['id'])->update(['is_release'=>$is_release]);
        if($data){
            return jsonReturn(1, []);
        }
        return jsonReturn(0, []);
    }
}